package com.situ.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;
import com.situ.web.service.UserService;

@WebServlet("/user")
public class UserController extends HttpServlet {
	private UserService userService = new UserService();

	// 访问这个servlet时候默认会访问这个service方法
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		// http://localhost:8080/Java1912WebStudy/student?method=findAll
		String method = req.getParameter("method");

		switch (method) {
		case "login":
			login(req, resp);
			break;
		default:
			break;
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		// select id,name,password from user where name='zhangsan' and password='123';
		User user = userService.login(name, password);
		if (user != null) {
			HttpSession session = req.getSession();
			//根据session里面是不是有user这个数据判断用户是不是已经登录
			session.setAttribute("user", user);
			resp.sendRedirect(req.getContextPath() + "/index.jsp");
		} else {
			resp.sendRedirect(req.getContextPath() + "/user_login.jsp");
		}
	}
}
